﻿using System;
using System.Net;
using System.Net.Sockets;

namespace GeneralDFS.Common.Network
{
    public class SocketHelper
    {
        /// <summary>
        /// 获得与IP PORT绑定后的socket.socket使用的是TCP流协议
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public static Socket GetSocket(String ip, int port)
        {
            try
            {
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Bind(localEndPoint);
                return socket;
            }
            catch (Exception ex)
            {
                LogUtil.LogError(ex.Message);
            }
            return null;
        }

        /// <summary>
        /// 获得与IP 和随机端口绑定后的socket。socket使用的是TCP流协议
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static Socket GetSocket(String ip)
        {
            try
            {
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(ip), 0);
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Bind(localEndPoint);
                return socket;

            }
            catch (Exception ex)
            {
                LogUtil.LogError(ex.Message);
            }
            return null;
        }
    }
}
